package juc;

public class P22 {
    Object a=new Object();
    Object b=new Object();
    public void A() throws InterruptedException {
        synchronized (a){
            System.out.println(Thread.currentThread().getName()+"拿到A，尝试获取B");
            Thread.sleep(1000);
            synchronized (b){
                System.out.println(Thread.currentThread().getName()+"拿到B");
            }
        }
    }

        public void B() throws InterruptedException {
        synchronized (b){
            System.out.println(Thread.currentThread().getName()+"拿到B，尝试获取A");
            Thread.sleep(1000);
            synchronized (a){
                System.out.println(Thread.currentThread().getName()+"拿到A");
            }
        }
    }
    public static void main(String[] args) {
        P22 p22=new P22();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    p22.A();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        },"UUU").start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    p22.B();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        },"YYY").start();
    }
}
